﻿@inherits BaseComponent

@if (Model != null && Model.HasItem)
{
    var items = Model.Items.Where(i => i.Visible).ToList();
    <div class="ant-toolbar">
        @if (items.Count > Model.ShowCount)
        {
            for (int i = 0; i < Model.ShowCount - 1; i++)
            {
                var item = items[i];
                var itemName = Language.GetString(item);
                if (item.Children != null && item.Children.Count > 0)
                {
                    var model = GetDropdownModel(itemName);
                    model.Items = item.Children;
                    <AntDropdown Context="Context" Model="model" />
                }
                else
                {
                    <KButton Name="@itemName" Enabled="item.Enabled" Type="@item.Style" Icon="@item.Icon" OnClick="e=>Model.OnItemClick?.Invoke(item)" />
                }
            }
            var more = GetDropdownModel(Language["Button.More"]);
            more.Items = items.Skip(Model.ShowCount - 1).ToList();
            <AntDropdown Context="Context" Model="more" />
        }
        else
        {
            foreach (var item in items)
            {
                var itemName = Language.GetString(item);
                if (item.Children != null && item.Children.Count > 0)
                {
                    var model = GetDropdownModel(itemName);
                    model.Items = item.Children;
                    <AntDropdown Context="Context" Model="model" />
                }
                else
                {
                    <KButton Name="@itemName" Enabled="item.Enabled" Type="@item.Style" Icon="@item.Icon" OnClick="e=>Model.OnItemClick?.Invoke(item)" />
                }
            }
        }
    </div>
}

@code {
    [Parameter] public ToolbarModel Model { get; set; }

    protected override void OnInitialized()
    {
        if (Model == null)
            return;

        Model.OnRefresh = StateChanged;
        base.OnInitialized();
    }

    private DropdownModel GetDropdownModel(string textButton)
    {
        return new DropdownModel
        {
            TextButton = textButton,
            OnItemClick = e=>
            {
                Model.OnItemClick?.Invoke(e);
                return Task.CompletedTask;
            }
        };
    }
}